package minh.bac.wcbrazil2014;

import java.io.File;
import java.util.ArrayList;

import minh.bac.wcbrazil2014.adapter.ViewPagerAdapter;
import minh.bac.wcbrazil2014.favorite.FavoriteFragment;
import minh.bac.wcbrazil2014.homnay.HomNayFragment;
import minh.bac.wcbrazil2014.listviewmatch.ListViewMatchFragment;
import minh.bac.wcbrazil2014.netsupport.ControlAsynctask;
import minh.bac.wcbrazil2014.netsupport.NetSupport;
import minh.bac.wcbrazil2014.netsupport.WCAsynctask;
import minh.bac.wcbrazil2014.news.NewsFragment;
import minh.bac.wcbrazil2014.shareface.ShareFaceFm;
import minh.bac.wcbrazil2014.thongke.ThongKeFragment;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.viewpagerindicator.TabPageIndicator;

public class HomeScreen extends ActionBarActivity implements
		NavigationDrawerFragment.NavigationDrawerCallbacks, ControlAsynctask {

	/**
	 * Fragment managing the behaviors, interactions and presentation of the
	 * navigation drawer.
	 */
	private NavigationDrawerFragment mNavigationDrawerFragment;

	/**
	 * Used to store the last screen title. For use in
	 * {@link #restoreActionBar()}.
	 */

	ProgressDialog mProgressDialog;
	static FragmentManager fragmentManager;
	Dialog_Exit dialogExit;
	private boolean TwoTimeBackClick = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.home_screen);
		ActionBar actionBar = getSupportActionBar();
		ColorDrawable colorDrawable = new ColorDrawable(
				Color.parseColor("#326295"));
		actionBar.setBackgroundDrawable(colorDrawable);
		//
		mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
				.findFragmentById(R.id.navigation_drawer);
		// Set up the drawer.
		mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
				(DrawerLayout) findViewById(R.id.drawer_layout));
		//
		fragmentManager = getSupportFragmentManager();
		File cacheDir = new File(getCacheDir(), "wcimgcachedir");
		if (!cacheDir.exists())
			cacheDir.mkdir();
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).memoryCache(new WeakMemoryCache()).threadPoolSize(4)
		// .memoryCacheSize(1048576 * 10)
				.discCache(new UnlimitedDiscCache(cacheDir))
				// .discCache(discCache)
				.denyCacheImageMultipleSizesInMemory().build();
		//
		ImageLoader.getInstance().init(config);
		// ////////////////////

		//
		if (NetSupport.isNetworkAvailable(HomeScreen.this)) {
			mProgressDialog = new ProgressDialog(HomeScreen.this);
			// mProgressDialog.setTitle("Loading");
			mProgressDialog.setMessage("Đợi em chút!!");
			mProgressDialog.show();
			WCAsynctask wcAsynctask = new WCAsynctask(HomeScreen.this, this);
			wcAsynctask.execute("http://naq.name.vn/f/WC2014/database.json");
		} else
		{
			Toast.makeText(this, "No connection", Toast.LENGTH_SHORT).show();
		}
		

	}

	@Override
	public void onNavigationDrawerItemSelected(int position) {
		// TODO Auto-generated method stub
		switch (position) {
		case 0:
			fragmentManager.beginTransaction()
					.replace(R.id.container, new PlaceholderFragment())
					.commit();

			break;
		case 1:
			break;
		case 2:
			fragmentManager
					.beginTransaction()
					.replace(
							R.id.container,
							NewsFragment
									.newInstace("http://us.24h.com.vn/world-cup-2014-c512.html"))
					.commit();
			break;
		case 3:
			fragmentManager
					.beginTransaction()
					.replace(
							R.id.container,
							NewsFragment
									.newInstace("http://worldcup.vnexpress.net/"))
					.commit();
			break;
		case 4:
			fragmentManager
					.beginTransaction()
					.replace(
							R.id.container,
							NewsFragment
									.newInstace("http://news.zing.vn/World-Cup-2014.html"))
					.commit();
			break;
		case 5:
			fragmentManager.beginTransaction()
					.replace(R.id.container, new ShareFaceFm()).commit();
			break;
		default:
			break;
		}
	}

	@Override
	public void doInCompleted(boolean flag) {
		// TODO Auto-generated method stub
		if (flag) {
			mProgressDialog.dismiss();
			//
			PlaceholderFragment placeholderFragment = new PlaceholderFragment();
			FragmentTransaction fragmentTransaction = getSupportFragmentManager()
					.beginTransaction();
			fragmentTransaction.add(R.id.container, placeholderFragment)
					.commit();
			fragmentTransaction.attach(placeholderFragment);
		} else {
			mProgressDialog.dismiss();
			PlaceholderFragment placeholderFragment = new PlaceholderFragment();
			FragmentTransaction fragmentTransaction = getSupportFragmentManager()
					.beginTransaction();
			fragmentTransaction.add(R.id.container, placeholderFragment)
					.commit();
			fragmentTransaction.attach(placeholderFragment);
			Toast.makeText(this, "failded", Toast.LENGTH_SHORT).show();
		}
	}

//	public void restoreActionBar() {
//		ActionBar actionBar = getSupportActionBar();
//		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
//		actionBar.setDisplayShowTitleEnabled(true);
//		// actionBar.setTitle(mTitle);
//	}	

	

	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {

		public PlaceholderFragment() {
		}

		private FragmentStatePagerAdapter mViewPagerAdapter;
		private ViewPager mViewPager;
		private ArrayList<Fragment> mViewPagerFMList;
		private TabPageIndicator mTabTitleIndicator;
		ProgressDialog mProgressDialog;

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			View rootView = inflater.inflate(R.layout.fragment_main, container,
					false);
			//
			mViewPager = (ViewPager) rootView.findViewById(R.id.pagerFm);
			mViewPager.setOffscreenPageLimit(4);
			mTabTitleIndicator = (TabPageIndicator) rootView
					.findViewById(R.id.indicatorTitleTab);
			mViewPagerFMList = new ArrayList<Fragment>();
			// load list fragment
			LoadFragment();
			mViewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager(),
					mViewPagerFMList);
			mViewPager.setAdapter(mViewPagerAdapter);
			// mViewPagerAdapter.notifyDataSetChanged();
			mTabTitleIndicator.setViewPager(mViewPager);
			//
			return rootView;
		}

		public void LoadFragment() {
			mViewPagerFMList.add(new ListViewMatchFragment());
			mViewPagerFMList.add(new HomNayFragment());
			mViewPagerFMList.add(new FavoriteFragment());
			mViewPagerFMList.add(new ThongKeFragment());
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			showDialogExit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void showDialogExit() {
		dialogExit = new Dialog_Exit(HomeScreen.this);
		dialogExit.show();
		// TODO Auto-generated method stub
//		AlertDialog.Builder adb = new Builder(this);
//		adb.setTitle("Oops!!");
//		adb.setMessage("Bạn có thật sự muốn thoát?");
//		adb.setIcon(R.drawable.ic_emblem_club_placeholder);
//		adb.setNegativeButton("Đồng ý!", new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// TODO Auto-generated method stub
//				finish();
//			}
//		});
//		adb.setPositiveButton("Hũy bỏ", new DialogInterface.OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface dialog, int which) {
//				// TODO Auto-generated method stub
//				dialog.dismiss();
//			}
//		});
//		AlertDialog ad = adb.create();
//		ad.show();

	}

	// @Override
	// public void onBackPressed() {
	// // TODO Auto-generated method stub
	// if (TwoTimeBackClick) {
	// super.onBackPressed();
	// return;
	// }
	// TwoTimeBackClick = true;
	// Toast.makeText(HomeScreen.this, "Bấm thêm lần nữa để thoát ",
	// Toast.LENGTH_SHORT).show();
	// Handler handler = new Handler();
	//
	// handler.postDelayed(new Runnable() {
	//
	// @Override
	// public void run() {
	// TwoTimeBackClick = false;
	// }
	// }, 2000);
	// }

}
